import React, { useState, useEffect, useRef } from "react";
import { Card, Row, Col } from "antd";
import ProForm, {
  ProFormSelect,
  ProFormDatePicker,
} from "@ant-design/pro-form";
import { PageContainer } from "@ant-design/pro-layout";
import { Line, Pie } from "@ant-design/plots";
import "./index.less";
import hospital_num from "../../../public/images/hospital_num.svg";
import work_num from "../../../public/images/work_num.svg";
import user_num from "../../../public/images/user_num.svg";
import check_num from "../../../public/images/check_num.svg";

import money from "../../../public/images/money.svg";
import people from "../../../public/images/people.svg";

import moment from "moment";
import { useModel } from "umi";
import {
  getStatistics,
  getRealTimeSituation,
  getTrend,
  getDisease,
  getDrug,
} from "@/api/home";
import { getHospitalList } from "@/api/hospital";

const Home = () => {
  const { initialState, setInitialState } = useModel("@@initialState");

  const [info, setInfo] = useState({});
  const [data, setData] = useState([]);
  const [data2, setData2] = useState([]);
  const [data3, setData3] = useState([]);
  const [inspectionList, setInspectionList] = useState([]);
  const [hospitalList, setHospitalList] = useState([]);
  const formRef = useRef();
  const formRef2 = useRef();
  const formRef3 = useRef();

  const fetchStatistics = async () => {
    if (initialState?.currentUser?.type === 2) {
      const sub = await getRealTimeSituation();
      setInfo({
        ...sub?.data,
      });
    } else {
      // const res = await getStatistics();
      const sub = await getRealTimeSituation();
      setInfo({
        // ...res?.data,
        ...sub?.data,
      });
    }
  };

  // 曲线图
  const fetchTrend = async () => {
    const fields = formRef.current?.getFieldsValue();
    const postData = {
      ...fields,
      month: moment(fields?.month).format("YYYY/MM"),
    };
    const res = await getTrend(postData);
    setData(res.data);
  };

  // 饼图
  const fetchPie2 = async () => {
    const fields = formRef2.current?.getFieldsValue();
    const postData = {
      ...fields,
      month: moment(fields?.month).format("YYYY/MM"),
    };
    const res = await getDisease(postData);
    setData2(res.data);
  };

  // 饼图
  const fetchPie3 = async () => {
    const fields = formRef3.current?.getFieldsValue();
    const postData = {
      ...fields,
      month: moment(fields?.month).format("YYYY/MM"),
    };
    const res = await getDrug(postData);
    setData3(res.data);
  };

  // 获取检验所
  const fetchInspectionList = async () => {
    const res = await getHospitalList({
      type: 3,
    });
    setInspectionList(res.data);
  };

  // 获取医院
  const fetchHospitalList = async () => {
    const res = await getHospitalList({
      parentId: initialState?.currentUser.hospitalId,
      type: 2,
    });
    setHospitalList(res.data);
  };

  const init = () => {
    formRef.current?.setFieldsValue({
      month: moment(),
    });
    formRef2.current?.setFieldsValue({
      month: moment(),
    });
    formRef3.current?.setFieldsValue({
      month: moment(),
    });
  };

  useEffect(() => {
    init();
    initialState?.currentUser?.type === 0 && fetchInspectionList();
    initialState?.currentUser?.type === 1 && fetchHospitalList();
    fetchStatistics();
    fetchTrend();
    fetchPie2();
    fetchPie3();
    document.body.scrollIntoView();
  }, []);
  const data1 = [
    {
      day: "06-01",
      num: 20,
      name: "检测人数",
    },
    {
      day: "06-02",
      num: 35,
      name: "检测人数",
    },
    {
      day: "06-03",
      num: 42,
      name: "检测人数",
    },

    {
      day: "06-01",
      num: 30,
      name: "病载检测",
    },
    {
      day: "06-02",
      num: 20,
      name: "病载检测",
    },
    {
      day: "06-03",
      num: 36,
      name: "病载检测",
    },

    {
      day: "06-01",
      num: 25,
      name: "耐药检测",
    },
    {
      day: "06-02",
      num: 40,
      name: "耐药检测",
    },
    {
      day: "06-03",
      num: 60,
      name: "耐药检测",
    },

    {
      day: "06-01",
      num: 50,
      name: "检测数量",
    },
    {
      day: "06-02",
      num: 80,
      name: "检测数量",
    },
    {
      day: "06-03",
      num: 20,
      name: "检测数量",
    },
  ];

  const config = {
    data,
    padding: "auto",
    xField: "day",
    yField: "num",
    seriesField: "name",
    xAxis: {},
    meta: {
      day: {
        alias: "时间",
      },
      // num: {
      //   alias: "检测人数",
      //   formatter: (val) => {
      //     return val + "人";
      //   },
      // },
    },
    smooth: true,
  };

  const dataPie1 = [
    {
      name: "病载含量：<50",
      num: 27,
    },
    {
      name: "病载含量：50-5000",
      num: 25,
    },
    {
      name: "病载含量：>5000",
      num: 18,
    },
  ];

  const configPie1 = {
    appendPadding: 10,
    data: data2,
    angleField: "num",
    colorField: "name",
    radius: 0.8,
    label: {
      type: "outer",
    },
    interactions: [
      {
        type: "element-active",
      },
    ],
  };

  const dataPie2 = [
    {
      name: "发现耐药",
      num: 27,
    },
    {
      name: "未发现耐药",
      num: 25,
    },
  ];

  const configPie2 = {
    appendPadding: 10,
    data: data3,
    angleField: "num",
    colorField: "name",
    radius: 0.8,
    label: {
      type: "outer",
    },
    interactions: [
      {
        type: "element-active",
      },
    ],
  };

  const getForm = (t, ref) => {
    const func = {
      1: fetchTrend,
      2: fetchPie2,
      3: fetchPie3,
    };
    return (
      <div>
        <ProForm layout="inline" formRef={ref} submitter={false}>
          {/* admin */}
          {initialState?.currentUser?.type === 0 && (
            <ProFormSelect
              placeholder="请选择检验所"
              name="inspectionId"
              label="检验所"
              allowClear
              fieldProps={{
                options: inspectionList,
                onChange: func[t],
                fieldNames: {
                  value: "id",
                  label: "name",
                },
              }}
            />
          )}
          {/* 质控中心 */}
          {initialState?.currentUser?.type === 1 && (
            <ProFormSelect
              placeholder="请选择医院"
              name="hospitalId"
              label="医院"
              allowClear
              fieldProps={{
                options: hospitalList,
                onChange: func[t],
                fieldNames: {
                  value: "id",
                  label: "name",
                },
              }}
            />
          )}

          <ProFormDatePicker
            label="月份"
            name="month"
            placeholder="请选择月份"
            fieldProps={{
              allowClear: false,
              format: "YYYY/MM",
              picker: "month",
              onChange: func[t],
            }}
          />
        </ProForm>
      </div>
    );
  };

  return (
    <PageContainer ghost>
      {initialState?.currentUser?.type !== 2 ? (
        <Row gutter={20}>
          <Col span={6}>
            <div className="item">
              <div>
                <span>当前医院数量</span>
                <h1>{info?.hospitalNum || 0}</h1>
              </div>
              <div className="right">
                <img src={hospital_num} alt="" />
              </div>
            </div>
          </Col>
          {initialState.currentUser.type !== 1 && (
            <Col span={6}>
              <div className="item">
                <div>
                  <span>检验所数据量</span>
                  <h1>{info?.inspectionOfficeNum || 0}</h1>
                </div>
                <div className="right green">
                  <img src={check_num} alt="" />
                </div>
              </div>
            </Col>
          )}

          <Col span={6}>
            <div className="item">
              <div>
                <span>当前患者数量</span>
                <h1>{info?.patientNum || 0}</h1>
              </div>
              <div className="right pink">
                <img src={work_num} alt="" />
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="item">
              <div>
                <span>当月检测数量</span>
                <h1>{info?.inspectionNum || 0}</h1>
              </div>
              <div className="right blue">
                <img src={user_num} alt="" />
              </div>
            </div>
          </Col>
        </Row>
      ) : null}

      <Card style={{ marginTop: 20, borderRadius: 10 }}>
        <h2>实时概况</h2>
        <Row>
          <Col span={6}>
            <div className="item-two">
              <div className="left">
                <img src={money} alt="" />
              </div>
              <div className="right">
                <span>采样数量</span>
                <h1>{info?.todaySamplingNum || 0}</h1>
                <p>
                  昨日：
                  {info?.yesterdaySamplingNum || 0}
                </p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="item-two">
              <div className="right">
                <span>检测数量</span>
                <h1>{info?.todayInspectionNum || 0}</h1>
                <p>昨日：{info?.yesterdayInspectionNum || 0}</p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="item-two">
              <div className="left">
                <img src={people} alt="" />
              </div>
              <div className="right">
                <span>新增患者</span>
                <h1>{info?.todayIncreasePatientNum || 0}</h1>
                <p>昨日：{info?.yesterdayIncreasePatientNum || 0}</p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="item-two">
              <div className="right">
                <span>检测人数</span>
                <h1>{info?.todayInspectionPersonNum || 0}</h1>
                <p>昨日：{info?.yesterdayInspectionPersonNum || 0}</p>
              </div>
            </div>
          </Col>
        </Row>
      </Card>

      <Card style={{ marginTop: 20, borderRadius: 10 }}>
        <h2 style={{ display: "flex", justifyContent: "space-between" }}>
          <span>检测趋势图</span>
          {getForm(1, formRef)}
        </h2>

        <Line {...config} />
      </Card>

      <Row gutter={20}>
        <Col span={12}>
          <Card style={{ marginTop: 20, borderRadius: 10 }}>
            <h2 style={{ display: "flex", justifyContent: "space-between" }}>
              <span>病载含量统计图</span>
              {getForm(2, formRef2)}
            </h2>
            <Pie {...configPie1} />
          </Card>
        </Col>
        <Col span={12}>
          <Card style={{ marginTop: 20, borderRadius: 10 }}>
            <h2 style={{ display: "flex", justifyContent: "space-between" }}>
              <span>耐药性统计图</span>
              {getForm(3, formRef3)}
            </h2>
            <Pie {...configPie2} />
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default Home;
